package com.cuixichang.minimalism.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuixichang.minimalism.acl.RelevanceDesign;
import com.cuixichang.minimalism.basal.base.Result;
import com.cuixichang.minimalism.basal.enums.IsEnableEnum;
import com.cuixichang.minimalism.basal.enums.ResponseCoderEnum;
import com.cuixichang.minimalism.core.security.userdetails.CredentialDetail;
import com.cuixichang.minimalism.core.security.utils.SecurityBeanUtil;
import com.cuixichang.minimalism.domain.IRouterCommandService;
import com.cuixichang.minimalism.transfer.dto.IRouterDTO;
import com.cuixichang.minimalism.transfer.factory.IRouterAssembler;
import com.cuixichang.minimalism.transfer.page.IRouterPageRequest;
import com.cuixichang.minimalism.transfer.page.IRouterRequest;
import com.cuixichang.minimalism.transfer.po.IRouter;
import com.cuixichang.minimalism.transfer.vo.IRouterVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import com.cuixichang.minimalism.service.IRouterService;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;

import java.util.stream.Collectors;

/**
 * 表控制层
 *
 * @author cuixichang
 * @date 2024-12-07
 */
@Api(tags = "路由功能接口")
@RestController
@RequestMapping("router")
@RequiredArgsConstructor
public class IRouterController {

    @Autowired
    private IRouterService iRouterService;
    @Autowired
    private IRouterCommandService iRouterCommandService;
    @Autowired
    private RelevanceDesign relevanceDesign;
    @GetMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "查询路由基本信息通过ID")
    public Result<IRouterVO> selectById(@PathVariable("id") Long id, @PathVariable("systemCode") String systemCode){
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        IRouterDTO router = iRouterCommandService.selectByIdHasPreCheck(id, systemCode, credentialDetail);
        return Result.ok("查询角色信息完成", IRouterAssembler.INSTANCT.convertVo(router));
    }

    @PostMapping("/info")
    @ApiOperation(value = "创建路由基本信息")
    public Result<IRouterVO> insert(@RequestBody IRouterRequest request) {
        IRouterDTO dto = IRouterAssembler.INSTANCT.convertDto(request);;
        IRouterDTO router = iRouterCommandService.insert(dto,SecurityBeanUtil.getCredentialDetail());
        return Result.ok("角色信息创建成功", IRouterAssembler.INSTANCT.convertVo(router));
    }

    @PutMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "修改路由基本信息通过ID")
    public Result<Boolean> updateById(@PathVariable Long id,
                                      @PathVariable("systemCode") String systemCode,
                                      @RequestBody IRouterRequest request){
        IRouterDTO dto = IRouterAssembler.INSTANCT.convertDto(request);
        dto.setId(id);
        dto.setCreateSystemCode(systemCode);
        return Result.ok(ResponseCoderEnum.Success.getDesc(), iRouterCommandService.updateByIdHasPreCheck(dto,SecurityBeanUtil.getCredentialDetail()));
    }

    @DeleteMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "删除路由基本信息通过ID")
    public Result<Boolean> deleteById(@PathVariable Long id,@PathVariable("systemCode") String systemCode){
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        return Result.ok(ResponseCoderEnum.Success.getDesc(), iRouterCommandService.deleteByIdHasPreCheck(id, systemCode,credentialDetail));
    }

    @GetMapping("/allow/{systemCode}")
    @ApiOperation(value = "查询路由是否允许使用(false:系统已存在账号;true:不存在或者为当前账号)")
    public Result<Boolean> allowUseRouter(@PathVariable("systemCode") String systemCode,
                                          @ApiParam(required = true, name = "routerUrl", value = "路由地址") String routerUrl,
                                          @ApiParam(required = true, name = "requestType", value = "请求类型") String requestType,
                                          @ApiParam(name = "matchRouterId", value = "匹配路由配置ID") Long matchRouterId) {
        return Result.ok(ResponseCoderEnum.Success.getDesc(), iRouterCommandService.allowUseRouter(routerUrl,requestType, systemCode, matchRouterId));
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页条件查询用户可操作路由信息")
    public Result<Page<IRouterVO>> selectPageByConditional(IRouterPageRequest request){
        IRouterDTO dto = IRouterAssembler.INSTANCT.convertDto(request);
        Page<IRouterDTO> page = iRouterCommandService.selectPageByConditional(dto, request.getPageNo(), request.getPageSize(),SecurityBeanUtil.getCredentialDetail());
        Page<IRouterVO> result = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        result.setRecords(page.getRecords().stream().map(IRouterAssembler.INSTANCT::convertVo).collect(Collectors.toList()));
        return Result.ok("分页查询用户路由信息完成",result);
    }

    @PostMapping("/relation/{bindingStatus}/{routerId}/{relationId}/{isRole}")
    @ApiOperation(value = "路由绑定（解绑）关系")
    public Result<Boolean> routerBindingStatus(@ApiParam(required = true, name = "bindingStatus", value = "1:绑定;0:解绑")  @PathVariable("bindingStatus") String bindingStatus,
                                               @ApiParam(required = true, name = "routerId", value = "路由Id") @PathVariable("routerId") Long routerId,
                                               @ApiParam(required = true, name = "relationId", value = "角色/权限Id")  @PathVariable("relationId") Long relationId,
                                               @ApiParam(required = true, name = "isRole", value = "1:角色;0:权限")  @PathVariable("isRole") String isRole){
        return Result.ok("操作成功",relevanceDesign.routerBindingStatus(routerId,relationId,
                IsEnableEnum.YES.getCode().toString().equals(isRole),
                IsEnableEnum.YES.getCode().toString().equals(bindingStatus), SecurityBeanUtil.getCredentialDetail()));
    }
}
